package controlleur;

import exceptions.DataSourceException;
import exceptions.EmployeNotFoundException;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import modele.Employe;
import modele.InterfaceEmployeModel;
import org.apache.struts.action.*;

public class EmployeAction extends GenericAction {

    public ActionForward addEmploye(ActionMapping mapping,
                                    ActionForm form,
                                    HttpServletRequest request,
                                    HttpServletResponse response)
            throws IOException,
                   ServletException {
        ActionMessages errors = new ActionMessages();
        ActionForward verif = null;
        String target = "success";

        // Teste sur l'identification de l'utilisateur
        if ((verif = verificationIdentification(mapping, request)) != null)
            return verif;

        // Annulation depuis la liste des employes
        if (isCancelled(request))
            return (mapping.findForward(target));

        // Parse du formulaire en employe
        Employe employe = getEmploye(form);

        try {
            InterfaceEmployeModel employeDB = getModel(request);
            employeDB.create(employe);
        } catch (DataSourceException e) {
            target = "error";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.database.error"));
        }

        // Signalement des erreurs eventuelles
        if (!errors.isEmpty())
            saveErrors(request, errors);

        // Transmission a la vue appropriee
        return (mapping.findForward(target));
    }

    public ActionForward editEmploye(ActionMapping mapping,
                                     ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response)
            throws IOException,
                   ServletException {
        ActionMessages errors = new ActionMessages();
        HttpSession session = request.getSession();
        ActionForward verif = null;
        String target = "success";

        // Teste sur l'identification de l'utilisateur
        if ((verif = verificationIdentification(mapping, request)) != null)
            return verif;

        // Annulation depuis la liste des employes
        if (isCancelled(request))
            return (mapping.findForward(target));

        try {
            InterfaceEmployeModel employeModel = getModel(request);
            Employe employe = employeModel.get(request.getParameter("username"));
            form = buildEmployeForm(employe);

            if (form != null)
                if ("request".equals(mapping.getScope()))
                    request.setAttribute(mapping.getAttribute(), form);
                else {
                    session = request.getSession();
                    session.setAttribute(mapping.getAttribute(), form);
                }
            else
                errors.add(ActionMessages.GLOBAL_MESSAGE,
                           new ActionMessage("errors.form.error"));

            employeModel.update(employe);
        } catch (EmployeNotFoundException e) {
            target = "error";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.login.unknow", e.getMessage()));
        } catch (DataSourceException s) {
            target = "error";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.database.error"));
        }

        // Retourner les erreurs eventuelles
        if (!errors.isEmpty())
            saveErrors(request, errors);

        // Transmettre la requete a la vue appropriee
        return (mapping.findForward(target));
    }

    public ActionForward updateEmploye(ActionMapping mapping,
                                       ActionForm form,
                                       HttpServletRequest request,
                                       HttpServletResponse response)
            throws IOException,
                   ServletException {

        ActionMessages errors = new ActionMessages();
        ActionForward verif = null;
        String target = "success";

        // Teste sur l'identification de l'utilisateur
        if ((verif = verificationIdentification(mapping, request)) != null)
            return verif;

        // Annulation depuis la liste des employes
        if (isCancelled(request))
            return (mapping.findForward(target));

        // Parse du formulaire en employe
        Employe employe = getEmploye(form);

        try {
            InterfaceEmployeModel employeModel = getModel(request);
            employeModel.update(employe);
        } catch (DataSourceException e) {
            target = "error";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.database.error"));
        }

        // Signaler les erreurs eventuelles
        if (!errors.isEmpty())
            saveErrors(request, errors);

        // Transmettre la requete a la vue appropriee
        return (mapping.findForward(target));
    }

    public ActionForward deleteEmploye(ActionMapping mapping,
                                       ActionForm form,
                                       HttpServletRequest request,
                                       HttpServletResponse response)
            throws IOException,
                   ServletException {

        ActionMessages errors = new ActionMessages();
        ActionForward verif = null;
        String target = "success";

        // Teste sur l'identification de l'utilisateur
        if ((verif = verificationIdentification(mapping, request)) != null)
            return verif;

        try {
            InterfaceEmployeModel employeDB = (InterfaceEmployeModel) getModel(request);
            employeDB.delete(request.getParameter("username"));
        } catch (DataSourceException e) {
            target = "error";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.database.error"));
        }

        // Signaler les erreurs eventuelles au formulaire originel
        if (!errors.isEmpty())
            saveErrors(request, errors);

        // Transmission a la vue appropriee
        return (mapping.findForward(target));
    }

    public ActionForward getEmployes(ActionMapping mapping,
                                     ActionForm form,
                                     HttpServletRequest request,
                                     HttpServletResponse response)
            throws IOException,
                   ServletException {
        ActionMessages errors = new ActionMessages();
        ActionForward verif = null;
        String target = "success";
        List<Employe> employes;

        // Teste sur l'identification de l'utilisateur
        if ((verif = verificationIdentification(mapping, request)) != null)
            return verif;

        try {
            InterfaceEmployeModel employeDB = getModel(request);
            employes = employeDB.getAll();
            request.setAttribute("employes", employes);
        } catch (DataSourceException e) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.database.error"));
            target = "login";
        }

        // Signalement des erreurs eventuelles
        if (!errors.isEmpty())
            saveErrors(request, errors);

        // Forward to the appropriate View    
        return (mapping.findForward(target));
    }

    private ActionForward verificationIdentification(ActionMapping mapping,
                                                     HttpServletRequest request) {
        ActionMessages errors = new ActionMessages();

        // Teste sur l'identification de l'utilisateur
        HttpSession session = request.getSession();

        if (session.getAttribute("USER") == null) {
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.login.required"));

            // Retourner les erreurs eventuelles au formulaire d'origine
            saveErrors(request, errors);

            // Si jamais l'utilisateur n'est pas loggé, alors
            // on retourne directement à la page de logon
            // avant d'effectuer la moindre requête
            return (mapping.findForward("login"));
        }
        return null;
    }
}